//
//  SoundProcessor.mm
//  TTPlayerLibrary
//
//  Created by TTPlayer on 11. 10. 14..
//  Copyright (c) 2011 ItBacc. All rights reserved.
//

#import "SoundProcessor.h"

#include "SoundTouch.h"

using namespace soundtouch;

@interface SoundTouchWrapper : NSObject {
    SoundTouch *soundTouch;
}

- (void)setChannels:(int)channels;
- (void)setSampleRate:(int)sampleRate;
- (void)putSamples:(const SAMPLETYPE*)samples nSamples:(uint)nSamples;
- (uint)receiveSamples:(SAMPLETYPE*)outBuffer maxSamples:(uint)maxSamples;
- (void)flush;
- (void)clear;

@end

@implementation SoundTouchWrapper

- (id)init
{
    self = [super init];
    if (self) {     
        soundTouch = new SoundTouch();
        soundTouch->setSetting(SETTING_USE_QUICKSEEK, TRUE);
        soundTouch->setSetting(SETTING_USE_AA_FILTER, FALSE);
    }
    
    return self;
}

- (void)dealloc{
    delete(soundTouch);
    [super dealloc];
}

- (void)setChannels:(int)channels{
    soundTouch->setChannels(channels);
}

- (void)setSampleRate:(int)sampleRate{
    soundTouch->setSampleRate(sampleRate);
}

- (void)putSamples:(const SAMPLETYPE*)samples nSamples:(uint)nSamples{
    soundTouch->putSamples(samples, nSamples);
}

- (uint)receiveSamples:(SAMPLETYPE*)outBuffer maxSamples:(uint)maxSamples{
    return soundTouch->receiveSamples(outBuffer, maxSamples);
}

- (void)flush{
    soundTouch->flush();
}

- (void)clear{
    soundTouch->clear();
}

@end


@implementation SoundProcessor

@synthesize channels=_channels;
@synthesize sampleRate=_sampleRate;

- (id)init
{
    self = [super init];
    if (self) {
        soundTouchWrapper = [[SoundTouchWrapper alloc] init];
        self.channels = 2;
        self.sampleRate = 44100; 
    }
    
    return self;
}

- (void)dealloc{
    [soundTouchWrapper release];
    [super dealloc];
}

- (void)clear{
    [soundTouchWrapper flush];
    [soundTouchWrapper clear];
}

- (void)setChannels:(int)channels{
    _channels = channels;
    [soundTouchWrapper setChannels:_channels];
    sampleSize = sizeof(SInt16)*_channels;
}

- (void)setSampleRate:(int)sampleRate{
    _sampleRate=sampleRate;
    [soundTouchWrapper setSampleRate:_sampleRate];
}

- (int)getFilterSound:(SInt16*)sampleBuffer bufferSize:(int)bufferSize{ 
    int totalBufferSize = 0;    
    int nSamples = 0;
    
    [soundTouchWrapper putSamples:sampleBuffer nSamples:bufferSize/sampleSize];
    
    do{
        nSamples = [soundTouchWrapper receiveSamples:sampleBuffer maxSamples:bufferSize/sampleSize];
        totalBufferSize += nSamples*sampleSize;
    }while (nSamples!=0);
    
    return totalBufferSize;
}

@end
